还有另一种使用JMockit模拟静态方法的方法(使用Delegate类)。我发现它更方便和优雅。 public class Service {
public String addSuffix(String str) { // method to be tested
return Utils.staticMethod(str);
}
}public class Utils {
public static String staticMethod(String s) { // method to be mocked
String suffix = DatabaseManager.findSuffix("default_suffix");
return s.concat(suffix);
}
}public class Test {
@Tested
Service service;
@Mocked
Utils utils; // @Mocked will make sure all methods will be mocked (including static methods)
@Test
public void test() {
new Expectations() {{
Utils.staticMethod(anyString); times = 1; result = new Delegate() {
public String staticMethod(String s) { // should have the same signature (method name and parameters) as Utils#staticMethod
return ""; // provide custom implementation for your Utils#staticMethod
}
}
}}
service.addSuffix("test_value");
new Verifications() {{
String s;
Utils.staticMethod(s = withCapture()); times = 1;
assertEquals("test_value", s); // assert that Service#addSuffix propagated "test_value" to Utils#staticMethod
}}
}
}参考:https://jmockit.github.io/tutorial/Mocking.html#delegateshttps://jmockit.github.io/tutorial/Mocking.html#withCapture
|